package config

import (
	"flag"
	"fmt"
	"github.com/go-ini/ini"
	"os"
	"path/filepath"
)

var (
	cfg      *ini.File
	APP_MODE string
)

func init() {
	// 根据env加载配置文件
	configFile := flag.String("config", "./Server/config/config_dev.ini", "Config File")
	var err error

	absConfigFile, err := filepath.Abs(*configFile)
	if err != nil {
		os.Exit(1)
	}

	cfg, err = ini.Load(absConfigFile)
	if err != nil {
		fmt.Printf("Fail to read file: %v", err)
		os.Exit(1)
	}

	APP_MODE = cfg.Section("").Key("env").String()

}

func GetConfigDns() string {
	dbSection := cfg.Section("db")
	return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&loc=Local&parseTime=True",
		dbSection.Key("user").String(),
		dbSection.Key("pass").String(),
		dbSection.Key("host").String(),
		dbSection.Key("port").String(),
		dbSection.Key("name").String())
}

func GetLogPath() string {
	path := cfg.Section("log").Key("path").String()
	if path == "" {
		path = "/tmp"
	}

	return path
}

func GetServerPort(defaultPort string) string {
	port := cfg.Section("server").Key("port").String()
	if port == "" {
		port = defaultPort
	}

	return port
}

func GetLogRes() bool {
	logRes, err := cfg.Section("log").Key("log_res").Bool()
	if err != nil {
		return false
	}
	return logRes
}
